<?php
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/


/**
 * @name MainTagCloudExtension
 * @copyright 2008  MP2P Technologies S.A.
 * 
 */

if ( ! defined( 'MEDIAWIKI' ) )
die();

require_once("DatabaseFunctions.php");

#install extension hook
$wgHooks['BeforePageDisplay'][] = 'CreateMainTagsCloud';

/**
 * @name generateTagCloudSearches
 * @abstract renders a tag cloud based on the count of TOP count popular searches
 * @param $SIZE_LIST
 * @param $SIZE_OFFSET
 */

function CreateMainTagsCloud ( ){
  global $wgCategory, $wgDBprefix, $wgScriptPath, $wgOut, $wgTitle, $wgArtistPop,$wgRequest;
  wfProfileIn("CreateMainTagsCloud");

  $SIZE_LIST = 40;
  $start_time = microtime(true);
  $dbr = wfGetDB( DB_SLAVE );
	
  $groupAttr = "artistKey";
  $fields = "s.Count w, s.Count w2, t.Artist Name";
  if ($wgCategory>0) $genreKey = "filter=genreKey,$wgCategory";
  else if ($wgTitle->mArtist!=null)
  {
	$wgArtistPop = 2;
	$sql = "select SQL_CACHE a.genreCrc crc, a.w/sum(filesTagsOk) w, sum(sources) Pop from ss_genres g inner join  (select SQL_CACHE genreCrc, sum(sources*filesTagsOk) w from ss_genres where artistkey='{$wgTitle->mArtistKey}' group by genreCrc order by w desc limit 20) a on g.genreCrc=a.genreCrc group by a.genreCrc order by w desc limit 5;";
	$res = $dbr->query ($sql);
	$i = $maxWeight = 0;
	$genreKey = "";
	while ($i<3 && $row = $dbr->fetchObject($res))
	{
		$wgArtistPop+=$row->Pop;
		$crc = $row->crc;
		if ($crc==3646436640) continue;
		$i++;
		$w = $row->w; 
		if ($maxWeight>0 && $w/$maxWeight<0.1) break;
		$genreKey .= ",$crc";
		if ($maxWeight == 0) { $maxWeight = $w; continue; }
		$weights .= " WHEN $crc THEN ".($w/$maxWeight);
	}
	$dbr->freeResult($res);
	if ($genreKey!=null) {
		$genreKey = "filter=genreKey$genreKey";
		if ($weights!=null) $weights = "*(CASE genreKey$weights ELSE 1 END)";
		$groupAttr = "genreArtist";
		$fields = "sum(s.Count) w, sum(s.Count$weights) as w2, common_string(3, 150, t.Artist) as Name";
		$group = "group by artistkey order by w2 desc";
	}
  }
  $wgArtistPop = log($wgArtistPop);
  $sql = "select SQL_CACHE $fields from searches s inner join ss_tags t on s.idtags=t.idtags where s.query='$genreKey;groupby=attr:$groupAttr;limit=40;select=idtags as idtags,genreKey as genreKey,sum(countTagsOk) as Count;groupsort=Count desc;!filter=countTagsOk,0;sort=expr:countTagsOk*TotalCount;maxquerytime=100;filter=type,1' $group";
  $mustSort = true;
  $filter = 1;
    
  $res = $dbr->query( $sql );
  
  //insert tags in array from database
  while ($row = $dbr->fetchObject( $res )) {
   $total_weight += $row->w;
   $tags[] = $row->Name.'@'.$row->w;
  }
  $dbr->freeResult ( $res );
 
  
  if ($tags !== null){
	if ($mustSort) natcasesort($tags);

	$cloud = '<ul>';
  
  
	// Increasing this number will make the words bigger; Decreasing will do reverse
	$factor = 0.5;
	// Smallest font size possible
	$starting_font_size = 8;
	$max_count = $total_weight/5;

	foreach ($tags as $key => $value)
	{
		$values = explode("@", $value);
		$x = round(($values[1] * 110) / $max_count) * $factor;
		if ($x<$filter) continue;
		//fix the max
		if ($x > 18) $x = 18;
		$font_size = $starting_font_size + $x.'px';
		
		$query_search = str_replace(' ', ' <wbr />',$values[0]);
		$cloud .= ' <li><a class="tag" style="font-size: '.$font_size.'" title="'.$values[0].'" href="'.createURL(URL_ARTIST, array($values[0])).'">'.$query_search."<wbr /></a></li> ";
  	}


        //TODO move out this menu from this extension, i know, this is a "chapuza"

        $menu_column = "<div class='menu_column1'> <h4 >p2p music<br />database</h4>
                <ul id='nav'>
                    <li><a href='/' > > advanced search</a></li>
                    <li><a href='/' >> browse tags</a></li>
                    <li><a href='/' >> top charts</a></li>
                </ul>
                </div>";

        $menu_column .= "<div class='menu_column2'> <h4>music<br />wiki</h4>
                <ul id='nav'>
                    <li><a href='/' >> create article</a></li>
                    <li><a href='/' >> browse wiki</a></li>
                    <li><a href='/' >> surprise me</a></li>
                </ul>
                </div>";

        $menu_column .= "<div class='menu_column3'> <h4>music<br />community</h4>
                <ul id='nav'>
                    <li><a href='/' >> sign up</a></li>
                    <li><a href='/' >> fan clubs</a></li>
                    <li><a href='/' >> active users</a></li>
                </ul>
                </div>";


        //control order to paint the menu_column depends on wich page we are located
         //if the user is not logged in , goto user login page
                $value = $wgRequest->getText( 'title' );
                $values = explode(":", $value);

                //var_dump($values);

                if ($values[1] == 'UserLogin'  ) {  //if user login dont paint the menu_column
                    // header( 'Location: /s/UserLogin');
                    $wgOut->setCloud("<div class='tagcloud'>$cloud</div>");

                }

                 elseif ($values[0] == 'Category' OR $values[1] == 'All') {  //if user login dont paint the menu_column
                    // header( 'Location: /s/UserLogin');
                    $wgOut->setCloud("<div class='tagcloud'>$menu_column $cloud</div>");

                }

                else {
                   $wgOut->setCloud("<div class='tagcloud'>$menu_column</div>");
                }
        


//	if ($wgTitle->mNamespace==NS_CATEGORY)
//	{
//		$wgOut->switchBocataMode(true);
//		$wgOut->addHTML("<div class='tagcloud' id='tagcloudBrowsetags'>$cloud</div>");
//	} else
//		$wgOut->setCloud("<div class='tagcloud'>$cloud</div>");
//        }
  wfProfileOut("CreateMainTagsCloud");
  return true;
}
}
